package com.hotel.front;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.POSCategoryLogic;
import com.hotel.BL.POSItemLogic;
import com.hotel.BL.POSLogic;
import com.hotel.BL.POSTaxLogic;
import com.hotel.BL.POSUnitLogic;

import data.POS;
import data.POSCategory;
import data.POSItem;
import data.POSTax;
import data.POSUnit;
import data.passingData.ResultData;

@SuppressWarnings("serial")
public class POSCategoriesService extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			String func = req.getParameter("func");
			if (func.equals("loadPOSTax")) {
				LoadPOSTax(req, resp);
			}
			else if (func.equals("loadPOSUnit")) {
				LoadPOSUnit(req, resp);
			}
			else if (func.equals("loadCategory")){
				loadCategory(req, resp);
			}
			else if (func.equals("loadItem")){
				loadItem(req, resp);
			}
			else if(func.equals("setFav")){
				setFav(req,resp);
			}
			else if(func.equals("getPOS")){
				GetPOS(req,resp);
			}
			else if(func.equals("getAllCategories")){
				GetAllCategories(req,resp);
			}
			else if(func.equals("getPOSCategoriesById")){
				GetPOSCategoriesById(req,resp);
			}
			else if(func.equals("getFilterCategory")){
				GetFilterCategory(req,resp);
			}
			else if(func.equals("addCategories")){
				AddCategories(req,resp);
			}
			else if(func.equals("addSubCategories")){
				AddSubCategories(req,resp);
			}
			else if(func.equals("editCategories")){
				EditPOSCategories(req,resp);
			}
			else if(func.equals("editStatusPOScategoriesById")){
				ChangeStatus(req,resp);
			}
			else if(func.equals("delCategories")){
				DeleteCategories(req,resp);
			}
			else if(func.equals("delSubCategories")){
				DeleteSubCategories(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void LoadPOSTax(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		List<POSTax> obj = new POSTaxLogic(req,resp).GetAllPOSTax(hotelId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSTax p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	private void LoadPOSUnit(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		List<POSUnit> obj = new POSUnitLogic(req,resp).GetAllPOSUnit(hotelId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSUnit p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	private void loadCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		long posId = Long.parseLong(req.getParameter("posId"));
		POSCategoryLogic catLogic = new POSCategoryLogic(req,resp);
		List<POSCategory> obj = catLogic.GetAllCategoryInPOS(posId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSCategory p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	private void loadItem(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long posId = Long.parseLong(req.getParameter("posId"));
		POSItemLogic itemLogic = new POSItemLogic(req,resp);
		List<POSItem> obj = itemLogic.GetAllPOSItemInPOS(hotelId,posId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSItem p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	//localhost:8080/POSProductService?func=setFav&item=&set=true
	private void setFav(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		long hotelId = 1;
		HttpSession session = req.getSession(true);
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		
		long itemId = Long.parseLong(req.getParameter("item"));
		boolean setF = Boolean.parseBoolean(req.getParameter("set"));
		POSItemLogic POSProductLogic = new POSItemLogic(req,resp);
		POSItem POSProduct = POSProductLogic.GetPOSItem(itemId);
		POSProduct.setFavourite((setF)?POSProductLogic.GetMaxPOSItemFavId(hotelId)+1:0);
		POSProduct = POSProductLogic.UpdatePOSItem(POSProduct);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(POSProduct));
	}
	
	private void GetPOS(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		Object obj = new POSLogic(req,resp).GetAllPOS(hotelId);
		Object objtax = new POSTaxLogic(req,resp).GetAllPOSTax(hotelId);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		List<Object> rsObj = Arrays.asList(obj,objtax);
		resp.getWriter().println(gson.toJson(rsObj));
	}
	
	private void GetFilterCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long posId = Long.parseLong(req.getParameter("posId"));
		POSCategoryLogic posCategoryLogic = new POSCategoryLogic(req,resp);
		List<POSCategory> categoryInPos = posCategoryLogic.GetAllCategories(hotelId,posId);
		List<HashMap<String,Object>> categoryParent = new ArrayList<HashMap<String,Object>>();
		for(int i = 0;i<categoryInPos.size();i++){
			int countparent = 0;
			boolean checkfor = true;
			HashMap<String,Object> categoryParentSet = new HashMap<String,Object>();
			categoryParentSet.put("avaliable", categoryInPos.get(i).isAvaliable());
			categoryParentSet.put("hotelId", hotelId);
			categoryParentSet.put("id", categoryInPos.get(i).getId());
			categoryParentSet.put("parentCategory", categoryInPos.get(i).getParentCategory());
			long cateIdCheck = categoryInPos.get(i).getParentCategory();
			while(checkfor){
				if(cateIdCheck!=0){
					countparent++;
					POSCategory categoryCheckP = posCategoryLogic.GetPOSCategory(cateIdCheck);
					if(categoryCheckP.getParentCategory()!=0){
						cateIdCheck = categoryCheckP.getParentCategory();
						countparent++;
					}else{
						checkfor = false;
					}
				}else{
					checkfor = false;
				}
		    }
			categoryParentSet.put("countparentCategory", countparent);
			categoryParentSet.put("posId", categoryInPos.get(i).getPOSId());
			categoryParentSet.put("status", categoryInPos.get(i).isStatus());
			categoryParentSet.put("subCategoryString", categoryInPos.get(i).getSubCategoryString());
			categoryParentSet.put("title", categoryInPos.get(i).getTitle());
			categoryParent.add(categoryParentSet);
		}	
		//Object obj = new POSCategoryLogic().GetAllCategories(hotelId,posId);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(categoryParent));
	}
	
	private void GetAllCategories(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long offset = Long.parseLong(req.getParameter("offset"));
		long line = Long.parseLong(req.getParameter("line"));
		long pointer = Long.parseLong(req.getParameter("pagePointer"));
		String posId = req.getParameter("posId");
		List<POSCategory> obj = null;
		Object s = null;
		double dataSize = 0.0;
		POSCategoryLogic posCategoryLogic = new POSCategoryLogic(req,resp);
		POSLogic posLogic = new POSLogic(req,resp);
		List<HashMap<String,Object>> category = new ArrayList<HashMap<String,Object>>();
		if(req.getParameter("categoryId")!=null){
			Long categoryId = Long.parseLong(req.getParameter("categoryId"));
			dataSize = posCategoryLogic.GetAllSubCategories(hotelId,categoryId).size();
			POSCategory categories = posCategoryLogic.GetPOSCategory(categoryId);
			if(categories!=null){
				if(categories.getSubCategoryString()!=null&&!categories.getSubCategoryString().equals("")){
					for(int i=0;i<categories.getSubCategory().size();i++){
						long numberPage = (line * pointer) - (line-1);
						if(category.size()==line){
							continue;
						}
						if(i>=(numberPage-1)){
							if(categories.getSubCategory().get(i).isAvaliable()!=false){
								HashMap<String,Object> categoryset = new HashMap<String,Object>();
								POS pos = posLogic.GetPOS(categories.getSubCategory().get(i).getPOSId());
								int productSize = new POSItemLogic(req,resp).GetAllPOSItemByCate(hotelId,String.valueOf(categories.getSubCategory().get(i).getId())).size();
								categoryset.put("id",categories.getSubCategory().get(i).getId());
								categoryset.put("title",categories.getSubCategory().get(i).getTitle());
								if(categories.getSubCategory().get(i).getSubCategoryString()!=null)
									if(!categories.getSubCategory().get(i).getSubCategoryString().equals(""))
										categoryset.put("subCategoryString",categories.getSubCategory().get(i).getSubCategory());
								categoryset.put("productIdString",productSize);
								categoryset.put("posTitle",pos.getTitle());
								categoryset.put("posId",categories.getSubCategory().get(i).getPOSId());
								categoryset.put("status",categories.getSubCategory().get(i).isStatus());
								categoryset.put("avaliable",categories.getSubCategory().get(i).isAvaliable());
								categoryset.put("categoryTitle",categories.getTitle());
								categoryset.put("categoryId", categories.getId());
								category.add(categoryset);
							}
						}
					}
				}
			}
		}else{
			obj = posCategoryLogic.GetAllCategoriesLimit(hotelId,offset,line,posId);
			dataSize = posCategoryLogic.GetAllCategories(hotelId,posId).size();
			for(int i=0;i<obj.size();i++){
				HashMap<String,Object> categoryset = new HashMap<String,Object>();
				POS pos = posLogic.GetPOS(obj.get(i).getPOSId());
				int productSize = new POSItemLogic(req,resp).GetAllPOSItemByCate(hotelId,String.valueOf(obj.get(i).getId())).size();
				categoryset.put("id",obj.get(i).getId());
				categoryset.put("title",obj.get(i).getTitle());
				if(obj.get(i).getSubCategoryString()!=null&&!obj.get(i).getSubCategoryString().equals("")){
					categoryset.put("subCategoryString",obj.get(i).getSubCategory());
				}
				categoryset.put("productIdString",productSize);
				categoryset.put("posTitle",pos.getTitle());
				categoryset.put("posId",obj.get(i).getPOSId());
				categoryset.put("status",obj.get(i).isStatus());
				categoryset.put("avaliable",obj.get(i).isAvaliable());
				category.add(categoryset);
			}
			
		}
		HashMap<String,Object> rs = new HashMap<String,Object>();
		rs.put("data", category);
		 s = rs;
		Gson gson = new Gson();
		List<Object> rsObj = Arrays.asList(dataSize,pointer,line,s);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsObj));
	}
	
	private void GetPOSCategoriesById(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		long id = Long.parseLong(req.getParameter("id"));
		POSCategory obj = new POSCategoryLogic(req,resp).GetPOSCategory(id);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void AddCategories(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		String title = req.getParameter("title");
		String pospoint = req.getParameter("pospoint");
		String taxuse = req.getParameter("taxuse");
		String description = req.getParameter("description");
		Object obj = new POSCategoryLogic(req,resp).AddCategories(hotelId,title,pospoint,taxuse,description);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void AddSubCategories(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		String title = req.getParameter("title");
		String description = req.getParameter("description");
		String pospoint = req.getParameter("pospoint");
		String taxuse = req.getParameter("taxuse");
		String idcategory = req.getParameter("idcategory");
		POSCategory obj = new POSCategoryLogic(req,resp).AddSubCategories(hotelId,title,pospoint,taxuse,description,idcategory);
		String idsub = String.valueOf(obj.getId());
		new POSCategoryLogic(req,resp).EditCategoriesforSub(Long.parseLong(idcategory),title,description,idsub);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void EditPOSCategories(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long categoryId = Long.parseLong(req.getParameter("id"));
		String title = req.getParameter("title");
		String description = req.getParameter("description");
		String taxuse = req.getParameter("taxuse");
		Object obj = new POSCategoryLogic(req,resp).EditCategories(categoryId,title,taxuse,description);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void ChangeStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long categoriesId = Long.parseLong(req.getParameter("categoriesId"));
		Object obj = new POSCategoryLogic(req,resp).ChangeStatus(categoriesId);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void DeleteCategories(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String categoryIdList = req.getParameter("categoriesId");
		POSCategoryLogic posCategoryLogic = new POSCategoryLogic(req,resp);
		for(int i = 0; i < categoryIdList.split(",").length ; i++){
			posCategoryLogic.DeleteCategories(Long.parseLong(categoryIdList.split(",")[i]));
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(true));
	}
	private void DeleteSubCategories(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String categoryIdList = req.getParameter("categoriesId");
		Object objSend = null;
		POSCategoryLogic posCategoryLogic = new POSCategoryLogic(req,resp);
		for(int i = 0; i < categoryIdList.split(",").length ; i++){
			POSCategory obj = posCategoryLogic.GetPOSCategory(Long.parseLong(categoryIdList.split(",")[i]));
			Long parentCategory = obj.getParentCategory();
			POSCategory objParent = posCategoryLogic.GetPOSCategory(parentCategory);
			String[] chAry = objParent.getSubCategoryString().split(",");
			String newSubCategory = "";
			for(int j = 0;j<chAry.length;j++){
				if(!chAry[j].equals(categoryIdList.split(",")[i])){
					newSubCategory += chAry[j]+",";
				}
			}
			if(newSubCategory!=null&&!newSubCategory.equals("")){
				newSubCategory = newSubCategory.substring(0, newSubCategory.length()-1);
			}
			posCategoryLogic.EditSubCategories(parentCategory,newSubCategory);
			objSend = posCategoryLogic.DeleteCategories(Long.parseLong(categoryIdList.split(",")[i]));
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(objSend));
	}
}